import HandleBtn from '@/components/HandleBar/btn';
import type { ProColumns, ProFormInstance } from '@/components/Pro/';
import { ProTable } from '@/components/Pro/';
import { parseArray } from '@/pages/Statistics/Battery/utils';
import { rowToColumns } from '@/pages/Statistics/DOD/utils';
import {
  statisticDodControllerExportDodDatas,
  statisticDodControllerGetDodList,
} from '@/services/ess/statisticDod';
import { downloadFetch } from '@/utils/downloadFile';
import { useIntl, useModel } from '@umijs/max';
import { DatePickerProps } from 'antd';
import dayjs from 'dayjs';
import _ from 'lodash';
import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';
import './Common.less';

type areaColumnsType = {
  title: string;
  dataIndex: string;
  key: string;
  hideInSearch: boolean;
};
const TableList = forwardRef((props, ref) => {
  const { initialState } = useModel('@@initialState');
  const intl = useIntl();
  const formRef = useRef<ProFormInstance>();

  const tableColumnsMap = new Map<string, string>([
    ['dod', intl.formatMessage({ id: 'statistics.analyze.titleS' })],
    ['dischargedEnergy', intl.formatMessage({ id: 'data.dailyDischarge' })],
    ['chargedEnergy', intl.formatMessage({ id: 'data.dailyCharge' })],
    ['maxSoc', intl.formatMessage({ id: 'statistics.analyze.todayMaxSoc' })],
    ['minSoc', intl.formatMessage({ id: 'statistics.analyze.todayMinSoc' })],
  ]);
  /**
   * 获得对应的columns
   * @param keys
   */
  const getAreaColumns = (keys: string[]): areaColumnsType[] => {
    return keys.map((item: string) => {
      const nameArr = item.split('_');
      return {
        title: `${nameArr[0]}_${tableColumnsMap.get(nameArr[1])}`,
        dataIndex: item,
        key: item,
        hideInSearch: true,
      };
    });
  };
  // 统计维度
  const [deviceVal, setDeviceVal] = useState();
  const treeData = useRef(null);
  useImperativeHandle(ref, () => ({
    download: () => {
      const params = formRef?.current?.getFieldsFormatValue?.() || {};
      if (initialState?.isArea) {
        const ans = parseArray(params.codes ? params.codes : deviceVal);
        params.pageSize = 20 * ans.id.length;
        params.areaIdList = ans.id.join(',');
      }
      delete params.codes;
      downloadFetch(statisticDodControllerExportDodDatas as any, params);
    },
  }));
  useEffect(() => {
    if (props.deviceTree?.length) {
      treeData.current = props.deviceTree;
      setDeviceVal(props.deviceTree[0].uniqueId);
    }
  }, [props.deviceTree]);

  // useEffect(() => {
  //   if (props.deviceTree?.length) {
  //     treeData.current = setDisabled([props.deviceTree[0]]);
  //     selectedType.current = 'ROOT';
  //     setDeviceVal(props.deviceTree[0].uniqueId);
  //   }
  // }, [props.deviceTree]);

  const disabledDate: DatePickerProps['disabledDate'] = (current, { from }) => {
    const disabled = current > dayjs();

    if (from) {
      return disabled || Math.abs(current.diff(from, 'days')) >= 90;
    }

    return disabled;
  };

  const columns: ProColumns[] = [
    {
      // search field
      title: intl.formatMessage({ id: 'statistics.income.select' }),
      dataIndex: 'date',
      hideInTable: true,
      initialValue: [dayjs().subtract(6, 'day'), dayjs()],
      valueType: 'dateRange',
      fieldProps: {
        disabledDate: disabledDate,
        allowClear: false,
      },
      search: {
        transform: (value) => {
          if (value) {
            return {
              startDate: value[0],
              endDate: value[1],
            };
          }
        },
      },
    } satisfies ProColumns<any, 'dateRange'>,
    {
      hideInSearch: !initialState?.isArea,
      title: intl.formatMessage({ id: 'statistics.work.dimensions' }),
      dataIndex: 'codes',
      key: 'codes',
      valueType: 'treeSelect',
      fieldProps: {
        maxCount: 100,
        maxTagCount: 'responsive',
        multiple: true,
        value: deviceVal,
        showSearch: true,
        treeData: treeData?.current,
        fieldNames: {
          label: 'deviceName',
          value: 'uniqueId',
          children: 'subDevices',
        },
        onChange: (...args) => {
          setDeviceVal(args[0]);
        },
      },
      hideInTable: true,
    },
    {
      title: intl.formatMessage({ id: 'hisCurve.no' }),
      valueType: 'index',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'global.date' }),
      dataIndex: 'date',
      hideInSearch: true,
    },
  ];
  const stationColumns = [
    {
      title: intl.formatMessage({ id: 'statistics.analyze.todayMaxSoc' }),
      dataIndex: 'maxSoc',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'statistics.analyze.todayMinSoc' }),
      dataIndex: 'minSoc',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'statistics.analyze.titleS' }),
      dataIndex: 'dod',
      hideInSearch: true,
    },

    {
      title: intl.formatMessage({ id: 'data.dailyDischarge' }),
      dataIndex: 'dischargedEnergy',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'data.dailyCharge' }),
      dataIndex: 'chargedEnergy',
      hideInSearch: true,
    },
  ];
  const [getColumns, setGetColumns] = useState([...columns, ...stationColumns]);
  const [elseColumns, setElseColumns] = useState(stationColumns);
  useEffect(() => {
    setGetColumns([...columns, ...elseColumns]);
  }, [deviceVal]);
  return (
    <div>
      <ProTable<API.StatisticDodPageVo, API.statisticDodControllerGetDodListParams>
        headerTitle=" "
        style={{ position: 'relative', zIndex: '10' }}
        formRef={formRef}
        rowKey={'date'}
        columns={getColumns}
        onReset={() => {
          if (initialState?.isArea) {
            setDeviceVal(props.deviceTree[0].uniqueId);
          }
          formRef?.current?.submit();
        }}
        // search={{
        //   span: { xs: 24, sm: 24, md: 12, lg: 12, xl: 12, xxl: 7 },
        // }}
        request={async (params) => {
          if (initialState?.isArea) {
            const ans = parseArray(params.codes ? params.codes : deviceVal);
            params.pageSize = 20 * ans.id.length;
            params.areaIdList = ans.id.join(',');
          }
          delete params.codes;
          const response = await statisticDodControllerGetDodList(params);
          if (response.success) {
            const forRes = rowToColumns(response.data.records);
            const keys = _.slice(Object.keys(forRes[0]), 2);
            if (initialState?.isArea) {
              setGetColumns([...columns, ...getAreaColumns(keys)]);
              setElseColumns(getAreaColumns(keys));
            } else {
              setGetColumns([...columns, ...stationColumns]);
              setElseColumns(stationColumns);
            }
            // table 有个隐含行为，response.data 里有 records，它会加上pageIndex字段
            return {
              data: initialState?.isArea ? forRes : response.data.records,
              success: response.success,
              total: initialState?.isArea
                ? Number(response.data.total) /
                  (typeof deviceVal === 'string' ? 1 : deviceVal?.length)
                : Number(response.data.total),
            };
          }
        }}
        search={{
          className: 'searchPosInline',
        }}
        toolbar={{
          className: 'toobalrZindex',
          actions: [
            // eslint-disable-next-line react/button-has-type
          ],
        }}
      />
    </div>
  );
});

export type ToolBarProps = {
  tableRef: React.MutableRefObject<{ download: () => void } | undefined>;
};

const ToolBarRender: React.FC<ToolBarProps> = ({ tableRef }) => {
  const intl = useIntl();
  return (
    <HandleBtn handleType="export" key="export" onClick={() => tableRef.current?.download()}>
      {intl.formatMessage({ id: 'statistics.common.export' })}
    </HandleBtn>
  );
};

export default TableList;
export { ToolBarRender };
